<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

<head>
    <th:block th:include="include :: header('执行区')"/>
    <meta charset="utf-8">
    <link th:href="@{/easyui/themes/default/easyui.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/easyui/themes/icon.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/easyui/demo/demo.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/selfcss/mainframe.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/codemirror/lib/codemirror.css}" rel="stylesheet" type="text/css"/>
    <script th:src="@{/codemirror/codemirror.js}" type="text/javascript"></script>
    <style>
        .easyui-layout .tabs-container .panel-body {
            background: #fff;
            border: 1px solid #e7eaec;
            border-radius: 2px;
            padding: 0 !important;
            position: relative;
        }

        .easyui-layout .pagination {
            display: inline-block;
            padding-left: 0;
            margin: 5px 0 !important;
            border-radius: 4px;
        }
    </style>
    <title>表数据&维护</title>
</head>

<body>
<div id="mainLayout" class="easyui-layout" data-options="fit: true">
    <input id="filterCondition" name="filterCondition" class="easyui-textbox" type="text" style="width:100%"
           data-options="prompt:'输入查询条件查询数据(不必带where)',
                    iconAlign:'left',
                    icons:[{
                        iconCls:'icon-search',
                        handler: function(e){
                            let value = $(e.data.target).textbox('getValue');
                            queryByCondition(value);
                        }
                    }]"/>
    <div style="padding:0px;height:calc(100% - 120px)">
        <table id='dg' style="width:100%;height:98%"></table>
    </div>
    <div id="pg" class="easyui-pagination">
    </div>
    <div id="operation" class="operation"></div>
</div>


<!-- ddl模块 -->
<div id="ddlDialog" class="easyui-dialog" maximized="true"
     closed="true" closable="true" modal="true">
    <input id="ddlTb" type="text" style="width:100%;height:100%" readonly>
</div>

<!-- 列模式模块 -->
<div id="columnModeDlg" class="easyui-dialog" maximized="true"
     closed="true" closable="true" modal="true">
    <div id="columnModeTable">
    </div>
</div>

<!-- sql模块 -->
<div id="sqlDlg" class="easyui-dialog" maximized="false"
     closed="true" closable="true" modal="true">
    <input id="sqlTb" type="text" style="width:600px;height:300px" readonly>
</div>

<th:block th:include="include :: footer"/>
<script th:src="@{/easyui/jquery.easyui.min.js}" type="text/javascript"></script>
<script th:src="@{/fly/fly.js}" type="text/javascript"></script>
<script th:src="@{/selfjs/FlyRequest.js}" type="text/javascript"></script>

<!-- 高亮   -->
<script th:src="@{/codemirror/mode/sql/sql.js}" type="text/javascript"></script>
<link th:href="@{/codemirror/addon/hint/show-hint.css}" rel="stylesheet"/>
<script th:src="@{/codemirror/addon/hint/sql-hint.js}" type="text/javascript"></script>
<script th:src="@{/codemirror/addon/hint/show-hint.js}" type="text/javascript"></script>

<script th:src="@{/commonjs/CommonParam.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/aes.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/AesUtil.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/Barrett.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/BigInt.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/pbkdf2.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/RSA.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/SHA.js}" type="text/javascript"></script>
<script th:inline="javascript">
    var prefix = ctx + "datamonitor/table";
    let tableName = [[${tableName}]];
    let databaseId = [[${databaseId}]];
    let primaryKey;
    let columnType;
    $(function () {
        let toolbar = [

            {
                text: 'DDL',
                iconCls: 'icon-diy-table2',
                handler: function () {
                    ddl();
                }
            },
            {
                text: '列模式',
                iconCls: 'icon-diy-column1',
                handler: function () {
                    columnMode();
                }
            }, {
                text: 'INSERT语句',
                iconCls: 'icon-diy-insert1',
                handler: function () {
                    generateInsertSql();
                }
            }, {
                text: 'UPDTAE语句',
                iconCls: 'icon-diy-update1',
                handler: function () {
                    generateUpdateSql();
                }
            }, {
                text: 'DELETE语句',
                iconCls: 'icon-diy-delete2',
                handler: function () {
                    generateDeleteSql();
                }
            }
        ];

        $('#ddlTb').textbox({
            multiline: true
        });
        $('#sqlTb').textbox({
            multiline: true
        });

        $('#dg').datagrid({
            data: []
            , columns: []
            , autoRowHeight: true
            , rownumbers: true
            , singleSelect: true
            , toolbar: toolbar
            , onSortColumn: function (sort, order) {
                let condition = $("#filterCondition").textbox('getValue');
                pagingList(1, COMMONPARAM_DEFAULTPAGESIZE, condition, sort, order);
            },
            onSelectAll: function (row) {
                setOperation(rows.length + 'Rows selected')
            },
            onSelect: function (index, row) {
                setOperation('1 Rows Selected')
            }
        });

        $('#pg').pagination({
            pageList: COMMONPARAM_PAGELIST,
            pageSize: COMMONPARAM_DEFAULTPAGESIZE,
            total: 0,
            pageNumber: 1,
            beforePageText: '第',
            afterPageText: '页    共 {pages} 页',
            displayMsg: '当前显示 {from} - {to}条记录,共{total}条记录'
        });

        $('#filterCondition').textbox('textbox').bind('keyup', function (e) {
            if (e.keyCode == 13) {
                let value = $("#filterCondition").textbox('getValue');
                queryByCondition(value);
            }
        });

        pagingList(1, COMMONPARAM_DEFAULTPAGESIZE);
    })
    ;

    function ddl() {
        var config = {
            url: prefix + "/ddl?tableName=" + tableName + "&databaseId=" + databaseId,
            type: "post",
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    $('#ddlDialog').dialog('open').dialog('setTitle', 'ddl');
                    $('#ddlTb').textbox('setText', result.data);
                    setOperation(tableName + " ddl")
                } else if (result.code == 301) {
                    setOperation(result.msg)
                    $.modal.alertWarning(result.msg);
                } else {
                    setOperation(result.msg)
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config)
    }


    function queryByCondition(condition) {
        pagingList(1, COMMONPARAM_DEFAULTPAGESIZE, condition);
    }

    function pagingList(pageNum, pageSize, condition, orderByColumn, isAsc) {
        let submitData = {};
        submitData['tableName'] = tableName;
        submitData['databaseId'] = databaseId;
        if (condition != undefined && condition.trim() != '') {
            submitData['condition'] = condition;
        }
        if (orderByColumn != undefined) {
            submitData['orderByColumn'] = orderByColumn;
        }

        if (isAsc != undefined) {
            submitData['isAsc'] = isAsc;
        }
        submitData['pageNum'] = pageNum;
        submitData['pageSize'] = pageSize;

        var config = {
            url: prefix + '/tableInfo/list',
            type: "post",
            dataType: "json",
            data: submitData,
            success: function (result) {
                if (result.code == 0) {
                    var resultList = result.data
                    primaryKey = resultList.primaryKey;
                    columnType = resultList.columnType;
                    $('#dg').datagrid({
                        data: resultList.rows
                        , columns: [resultList.columns]
                    });
                    // 设置操作类型
                    setOperation(resultList.executeSql)
                    $('#pg').pagination({
                        pageList: COMMONPARAM_PAGELIST,
                        pageSize: resultList.pageSize,
                        total: resultList.total,
                        pageNumber: resultList.pageNum,
                        beforePageText: '第',
                        afterPageText: '页    共 {pages} 页',
                        displayMsg: '当前显示 {from} - {to}条记录,共{total}条记录',
                        onSelectPage: function (pageNum, pageSize) {
                            pagingList(pageNum, pageSize, condition);//选择第几页的时候，就刷新
                        }
                    });
                } else if (result.code == 301) {
                    setOperation(result.msg)
                    $.modal.alertWarning(result.msg);
                } else {
                    setOperation(result.msg)
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config)
    }

    function columnMode() {
        let row = $('#dg').datagrid('getSelected');
        if (row) {
            let table = "<table cellpadding='5'>"
            for (let key in row) {
                console.log(key + ":" + row[key]);
                table += "<tr>";
                table += "<td>" + key + ":</td>";
                table += "<td>" + row[key] + "</td>";
                table += "</tr>";
            }
            table += "</table>";
            $('#columnModeDlg').dialog('open').dialog('setTitle', '列模式');
            $('#columnModeTable').html(table);

        } else {
            $.modal.msgWarning("请选择一条记录")
        }
    }

    function generateInsertSql() {
        let row = $('#dg').datagrid('getSelected');
        if (row) {
            let sql = 'insert into ' + tableName + ' (';
            for (let key in row) {
                if ('RN' == key) {
                    continue;
                }
                sql += key + ', ';
            }
            sql = sql.substring(0, sql.length - 2) + ') values (';
            for (let key in row) {
                //oracle的rn就不展示了
                if ('RN' == key) {
                    continue;
                }
                if (row[key] == null) {
                    sql += row[key] + ', ';
                } else {
                    if (columnType[key] == 'int' || columnType[key] == 'bigint' || columnType[key] == 'number' || columnType[key] == 'int4' ||
                        columnType[key] == 'int8') {
                        sql += row[key] + ', ';
                    } else {
                        sql += '\'' + row[key] + '\', ';
                    }
                }
            }
            sql = sql.substring(0, sql.length - 2) + ')';
            $('#sqlDlg').dialog('open').dialog('setTitle', 'insert语句');
            $('#sqlTb').textbox('setText', sql);

        } else {
            $.modal.msgWarning("请选择一条记录")
        }
    }

    function generateUpdateSql() {
        let row = $('#dg').datagrid('getSelected');
        if (row) {
            let sql = 'update ' + tableName + ' set ';
            let columnStr = '';
            let where = 'where ';
            for (let key in row) {
                //oracle的rn就不展示了
                if ('RN' == key) {
                    continue;
                }

                let value = '';
                if (row[key] == null) {
                    value = row[key] + ' ';
                } else {
                    if (columnType[key] == 'int' || columnType[key] == 'bigint' || columnType[key] == 'number' || columnType[key] == 'int4' ||
                        columnType[key] == 'int8') {
                        value = row[key] + ' ';
                    } else {
                        value = '\'' + row[key] + '\' ';
                    }
                }

                if (key == primaryKey) {
                    where += key + ' = ' + value + 'and ';
                } else {
                    columnStr += key + ' = ' + value + ', ';
                }
            }
            if (columnStr.length > 2) {
                sql = sql + columnStr.substring(0, columnStr.length - 2) + ' ' + where.substring(0, where.length - 4);
            } else {
                sql = sql + where.substring(0, where.length - 4);
            }

            $('#sqlDlg').dialog('open').dialog('setTitle', 'update语句');
            $('#sqlTb').textbox('setText', sql);

        } else {
            $.modal.msgWarning("请选择一条记录")
        }
    }

    function generateDeleteSql() {
        let row = $('#dg').datagrid('getSelected');
        if (row) {
            let sql = 'delete from ' + tableName + '';
            let where = 'where ';
            for (let key in row) {
                //oracle的rn就不展示了
                if ('RN' == key) {
                    continue;
                }

                let value = '';
                if (row[key] == null) {
                    value = row[key] + ' ';
                } else {
                    if (columnType[key] == 'int' || columnType[key] == 'bigint' || columnType[key] == 'number' || columnType[key] == 'int4' ||
                        columnType[key] == 'int8') {
                        value = row[key] + ' ';
                    } else {
                        value = '\'' + row[key] + '\' ';
                    }
                }

                if (key == primaryKey) {
                    where += key + ' = ' + value + 'and ';
                }
            }
            sql = sql + ' ' + where.substring(0, where.length - 4);
            $('#sqlDlg').dialog('open').dialog('setTitle', 'delete语句');
            $('#sqlTb').textbox('setText', sql);

        } else {
            $.modal.msgWarning("请选择一条记录")
        }
    }

    function setOperation(operation) {
        $('#operation').text(operation)
    }

</script>
</body>